package controller;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.UserGroup;

import core.*;

public class EditUserGroup extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static private PgSQL db = PgSQL.getInstance(); 

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CurrentUser user = new CurrentUser(request);
		if(!user.getGroup().isAdministrator()){
			View.showMessage(request, response, "You have no permission here.", "back");
			return;
		}
		
		ArrayList<UserGroup> system_grouplist = new ArrayList<UserGroup>();
		ArrayList<UserGroup> normal_grouplist = new ArrayList<UserGroup>();
		
		try{
			ResultSet rs = db.query("SELECT * FROM qz_usergroup ORDER BY groupid");
			while(rs.next()){
				UserGroup group = new UserGroup();
				group.setGroupId(rs.getInt(1));
				group.setGroupName(rs.getString(2));
				group.setPermission(rs.getInt(3));
				
				if(group.getGroupId() <= 2){
					system_grouplist.add(group);
				}else{
					normal_grouplist.add(group);
				}
			}

			if(normal_grouplist.isEmpty()){
				UserGroup blank_row = new UserGroup();
				blank_row.setGroupName("");
				normal_grouplist.add(blank_row);
			}
			
			request.setAttribute("system_grouplist[]", system_grouplist.toArray(new UserGroup[0]));
			request.setAttribute("normal_grouplist[]", normal_grouplist.toArray(new UserGroup[0]));
			
			View.show(request, response, "edit_usergroup");
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CurrentUser user = new CurrentUser(request);
		if(!user.getGroup().isAdministrator()){
			View.showMessage(request, response, "You have no permission to edit usergroups.", "back");
			return;
		}
		
		String[] ids = request.getParameterValues("id[]");
		String[] names = request.getParameterValues("name[]");
		String[] perms = request.getParameterValues("perm[]");
		
		if(ids.length <= 0){
			View.showMessage(request, response, "Illegal Operation.", "back");
		}
		

		LinkedList<Integer> existed_ids = new LinkedList<Integer>();		
		ResultSet rs = db.query("SELECT groupid FROM qz_usergroup");
		try{
			while(rs.next()){
				existed_ids.add(rs.getInt(1));
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		
		for(int i = 0; i < ids.length; i++){			
			if(names[i] == null || names[i].isEmpty()){
				continue;
			}
			
			int id = Tool.intval(ids[i]);
			if(id < 0){
				continue;
			}
			
			if(existed_ids.contains(id)){
				existed_ids.remove(new Integer(id));
				
				try{
					PreparedStatement ps = db.prepareStatement("UPDATE qz_usergroup SET groupname=?,permission=? WHERE groupid=? AND permission<>-1");
					ps.setString(1, names[i]);
					ps.setInt(2, Tool.intval(perms[i]));
					ps.setInt(3, id);
					ps.executeUpdate();
				}catch(SQLException e){
					e.printStackTrace();
				}
				
			}else{
				try{
					PreparedStatement ps = db.prepareStatement("INSERT INTO qz_usergroup (groupid,groupname,permission) VALUES (nextval('groupid'),?,?)");
					ps.setString(1, names[i]);
					ps.setInt(2, Tool.intval(perms[i]));
					ps.executeUpdate();
				}catch(SQLException e){
					e.printStackTrace();
				}
			}
		}
		
		Iterator<Integer> iter = existed_ids.iterator();
		while(iter.hasNext()){
			int id = iter.next();
			db.update("DELETE FROM qz_usergroup WHERE groupid=" + id);
		}
		
		View.showMessage(request, response, "Your configuration has been successfully saved.", "back");
	}
}
